﻿using Microsoft.EntityFrameworkCore;
using ContentmanagementBase.Domain;
using ContentmanagementBase.Domain.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Threading;

namespace ContentmanagementBase.Infrastructure
{
    public class ContentManagementDBContext : DbContext
    {
        public ContentManagementDBContext(DbContextOptions options) : base(options)
        {
        }

        #region DbSet属性
        /// <summary>
        /// 医院管理
        /// </summary>
        public DbSet<HospitalManagementModel> HospitalManagements { get; set; }

        /// <summary>
        /// 科室管理
        /// </summary>
        public DbSet<DepartmentManagementModel> DepartmentManagements { get; set; }

        /// <summary>
        /// 轮播图
        /// </summary>
        public DbSet<CarouelChartModel> CarouelCharts { get; set; }

        /// <summary>
        /// 科普疾病
        /// </summary>
        public DbSet<PopularScienceDiseaseModel> PopularScienceDiseases { get; set; }

        /// <summary>
        /// 药房管理
        /// </summary>
        public DbSet<PharmacyManagementModel> PharmacyManagements { get; set; }

        /// <summary>
        /// 问题管理
        /// </summary>
        public DbSet<ProblemManagementModel> ProblemManagements { get; set; }
        #endregion

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 配置所有实体的软删除过滤器
            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                // 检查实体是否继承自BaseEntity
                if (typeof(BaseEntity).IsAssignableFrom(entityType.ClrType))
                {
                    var parameter = Expression.Parameter(entityType.ClrType, "e");
                    var property = Expression.Property(parameter, "IsDeleted");
                    var constant = Expression.Constant(false);
                    var body = Expression.Equal(property, constant);
                    var lambda = Expression.Lambda(body, parameter);

                    modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambda);
                }
            }

            // 配置枚举类型映射为字符串
            modelBuilder.Entity<HospitalManagementModel>()
                .Property(h => h.HospitalGrade)
                .HasConversion<string>();

            modelBuilder.Entity<HospitalManagementModel>()
                .Property(h => h.HospitalType)
                .HasConversion<string>();
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            UpdateAuditFields();
            return base.SaveChangesAsync(cancellationToken);
        }

        public override int SaveChanges()
        {
            UpdateAuditFields();
            return base.SaveChanges();
        }

        private void UpdateAuditFields()
        {
            var entries = ChangeTracker.Entries()
                .Where(e => e.Entity is BaseEntity && (e.State == EntityState.Added || e.State == EntityState.Modified));

            foreach (var entry in entries)
            {
                var entity = (BaseEntity)entry.Entity;

                if (entry.State == EntityState.Added)
                {
                    entity.CreatedTime = DateTime.Now;
                    // CreatedBy应该从当前用户上下文中获取，这里暂时设为0
                    entity.CreatedBy = 0;
                }
                else
                {
                    entity.UpdatedTime = DateTime.Now;
                    // UpdatedBy应该从当前用户上下文中获取，这里暂时设为0
                    entity.UpdatedBy = 0;
                }
            }
        }
    }
}
